#!/usr/local/bin/python3
# -*- coding: UTF-8 -*-
import requests
import os,re,IPy,time,random

def CDNlist(ipC):
    Default=False
    CDN = open('CDN_IPlist.txt').read().split('\n')
    for x in CDN:
        CDN_ip=IPy.IP(x)
        boolIP=(ipC in CDN_ip)
        Default=(Default or boolIP)
    return Default

def kuaishou(url,DATA):
    HEAD = {'X-REQUESTID': '1382677768', 'User-Agent': 'kwai-android', 'Connection': 'keep-alive',
            'Accept-Language': 'zh-cn', 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': '145',
            'Accept-Encoding': 'gzip', 'Pragma': 'no-cache'}
    r = requests.post(url, headers=HEAD, data=DATA)

    kuaishou_R = r.json()['feeds'][0]['main_mv_urls'][0]['cdn']
    return kuaishou_R

def dnsR(domian):
    ns=os.popen('nslookup % s ' % domian).read()
    if ns.find('Name:') == -1:
        return []
    else:
        ns=ns[ns.find('Name:'):]
        ip = re.findall('\d+\.\d+\.\d+\.\d+', ns)
        return ip
def aipai(aipai_URL):
    try:
        r = requests.get(url=aipai_URL)
        DDurl = r.json()['data']['assetInfo']['flv']
        rr = requests.get(url=DDurl,allow_redirects=False)#请求调度，302不自动跳转，捕获响应头中的location
        domain=rr.headers["Location"][7:].split("/")[0]#取出url中的host位
        video=rr.headers["Location"]
        return domain,video
    except:
        return "打开失败"


def main(URL):
    aipaiDomian,video=aipai(URL)
    aipai_IP=dnsR(aipaiDomian)
    if len(aipai_IP) == 0:
        flag = "无解析结果"
    else:
        if CDNlist(aipai_IP[0]):
            # print(miaopai_ip)
            flag = '网内'
        else:
            flag = '出网'
    return (video, flag, "<br>".join(aipai_IP))

if __name__ == '__main__':
    #爱拍调度url
    RAMD = str(random.randint(46830000, 46831000))
    URL='http://m.aipai.com/mobile/apps/apps_module-auxplayer_func-indexDataNew_os-1_assetId-%s.html' % RAMD
    for i in range(10):
        t=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        res = main(URL)
        print('%s\t%s\t%s\n' % res)
        fLog=open('/var/www/html/short_video/%sShortVideoLog.txt'% time.strftime("%Y-%m-%d", time.localtime()),'a' )
        fLog.write(t+'\t爱拍\t%s\t%s\t%s\n' % res)
        fLog.close()